package org.zn.note.common.util;

/**
 * @ClassName HexUtil
 * @Author zn
 * @Date 2020/3/13 11:58
 **/
public class HexUtil {

    /**
     * 十六进制的字符串 --> byte[] （"FF" --> 0xFF）
     *
     * @param str
     * @return
     */
    public static byte[] hexStrToBytes(String str) {
        if (null == str || str.trim().length() == 0) {
            return null;
        }
        byte[] bytes = new byte[str.length() / 2];
        for (int i = 0; i < str.length() / 2; i++) {
            String subStr = str.substring(i * 2, i * 2 + 2);
            bytes[i] = (byte) Integer.parseInt(subStr, 16);
        }
        return bytes;
    }

    /**
     * byte[] --> 十六进制的字符串 (0xFF --> "FF")
     *
     * @param bytes
     * @return
     */
    public static String hexBytesToStr(byte[] bytes) {
        if (null == bytes) {
            return null;
        }
        StringBuilder buf = new StringBuilder(bytes.length * 2);
        for (byte b : bytes) {
            buf.append(String.format("%02X", new Integer(b & 0xff)));
        }
        return buf.toString();
    }

    public static void printBytesHex(byte[] bytes) {
        for (byte b : bytes) {
            System.out.print("0x" + String.format("%02X", new Integer(b & 0xff)) + " ");
        }
        System.out.println();
    }
}
